<template>
  <el-input
    v-model="value[props.optionListSetting.valueProp]"
    :id="props.formCtrlId"
    :size="props.size"
    :placeholder="props.inputPlaceholder"
    @blur="value[props.optionListSetting.valueProp] = $event.target.value"
    readonly="readonly"
  >
    <template #prepend>
      <el-select
        v-model="value"
        :value-key="props.optionListSetting.labelProp"
        :id="'w' + props.formCtrlId"
        :name="'w' + props.formCtrlId"
        :size="props.size"
        @change="mySubmit"
        :style="'width:' + props.selectWidth + 'px'"
        :placeholder="props.selectPlaceholder"
        @blur="blurInput()"
      >
        <template v-for="(item, key) in props.optionList" :key="key">
          <el-option
            :label="item[props.optionListSetting.labelProp]"
            :value="item"
          ></el-option>
        </template>
      </el-select>
    </template>
  </el-input>
</template>

<script lang="ts" setup>
import FormItemCtrl from "@/components/form/formItem/FormItemCtrl";
import { BaseFormItem } from "@/components/form/formItem/FormItemMeta";

export interface OptionListSetting {
  labelProp: string;
  valueProp: string;
}
// vue3 script setup 暂时不允许在单独的文件中定义props接口.
// vue3 的bug 导致接口所继承的属性与方法不可读.
export interface SelectDropDownProps extends BaseFormItem {
  modelValue: string | number | Array<unknown> | null | Record<string, unknown>;
  formCtrlId?: number; // 控件id, 区分组件
  colName?: string; // 字段名称
  isClear?: boolean; // 连续添加是否需要清空该字段
  controlType?: string; // 控件类型
  size?: string; // 尺寸 medium / small / mini
  optionList?: Array<unknown>; // 备用选项
  validateEvent?: boolean; // 输入时是否触发表单的校验
  selectWidth?: string;
  inputPlaceholder?: string;
  selectPlaceholder?: string;
  showWordLimit?: boolean; // 是否显示输入字数统计
  clearable?: boolean; // 是否显示清空标记
  resize?: string; // 是否能被用户缩放 none, both, horizontal, vertical
  optionListSetting?: OptionListSetting;
}

const props = withDefaults(defineProps<SelectDropDownProps>(), {
  modelValue: "",
  formCtrlId: 10001,
  colName: "no",
  isClear: true,
  size: "default",
  controlType: "text",
  optionList: () => [],
  validateEvent: true,
  selectWidth: "120",
  inputPlaceholder: "编号",
  selectPlaceholder: "名称",
  showWordLimit: true,
  clearable: true,
  resize: "none",
  optionListSetting: () => {
    return { labelProp: "label", valueProp: "value" };
  },
});

const blurInput = async () => {
  await setTimeout(() => {
    const inputSelect = document.getElementById(
      props.formCtrlId + ""
    ) as HTMLElement;
    inputSelect.focus();
    inputSelect.blur();
  }, 200);
};

const emit = defineEmits(["update:modelValue", "myChange", "input", "change"]);
const { value, mySubmit } = FormItemCtrl(props, emit);
</script>
